//
//  HotelHomeController.swift
//  AirTravel
//
//  Created by apple on 2021/7/12.
//

import UIKit
import JXBanner
import JXPageControl
import FWPopupView
import MapKit
import CoreLocation
import Moya
import SwiftyJSON

class HotelHomeController: UIViewController {
    
    @IBOutlet weak var topLine: NSLayoutConstraint!
    @IBOutlet weak var tabView: UITableView!
    let identifyBanner = "HomeBannerCell"
    let identifyPC = "Pure1Cell"
    let locationManager = CLLocationManager()
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var number = 0
    var currCity = ""
    var chooseCity = ""
    
    var areaId = ""
    var cityId = ""
    var time1 = ""
    var time2 = ""
    var day = "0"
    //间数，成人，儿童
    var jian = "0"
    var cr = "0"
    var er = "0"
    var seachStr = ""
    var page = 1
    
    var priceList : Array<Any>?
    var priceDic : Dictionary<String,Any>?
    var starDic : Dictionary<String,Any>?
    var dataSouce = [NSDictionary]()
    var mutDataDic = Dictionary<Int, NSArray>()
    
    lazy var banner: JXBanner = {
        let banner = JXBanner()
        banner.placeholderImgView.image = UIImage(named: "banner_placeholder")
        banner.delegate = self
        banner.tag = 0
        banner.dataSource = self
        banner.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 203)
        return banner
    }()
    
    lazy var guessLikeView: HomeGuessLikeModel = {
        let iconView = HomeGuessLikeModel()
        iconView.delegate = self
        iconView .setUpdata(array: [])
        return iconView
    }()
    
    lazy var calendarSelectView: CalendarSelectView = {
        let customPopupView = Bundle.main.loadNibNamed("CalendarSelectView", owner: self, options: nil)?.last as! CalendarSelectView
        customPopupView.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 0.8)
        customPopupView.setUpUI()
        return customPopupView
    }()
    
    lazy var homePopupView: StayInView = {
        let customPopupView = StayInView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 350))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    lazy var priceStarView: PriceStarView = {
        let customPopupView = PriceStarView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 350))
        customPopupView.tag = 1
        customPopupView.delegate = self
        return customPopupView
    }()
    
    lazy var switchAddressView: SwitchAddressView = {
        let customPopupView = SwitchAddressView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 0.6))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.addObserver(self, selector: #selector(calendar), name: Notification.Name("CalendarSelectView"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(gotoHotel(dic:)), name: Notification.Name("GOTOHOTEL"), object: nil)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        self.locationStart()
        if SCREEN_HEIGHT >= 812 {
            self.topLine.constant = 88
        }else{
            self.topLine.constant = 64
        }
        
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.separatorStyle = .none
        self.tabView.register(UINib.init(nibName: "HomeBannerCell", bundle: nil), forCellReuseIdentifier: identifyBanner)
        self.tabView.register(UINib.init(nibName: "Pure1Cell", bundle: nil), forCellReuseIdentifier: identifyPC)
        if #available(iOS 11.0, *) {
            self.tabView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = true
        }
        //获取日期格式化对象
        let dateFormatter=DateFormatter.init()
        dateFormatter.dateFormat="yyyy-MM-dd"
        self.time1 = dateFormatter.string(from: Date())
        let calendar = Calendar.current
        let date1 = calendar.date(byAdding: .day, value: 1, to: Date())!
        self.time2 = dateFormatter.string(from: date1)
        self.day = "1"
        
        self.tabView.es.addPullToRefresh {[weak self] in
            self?.page = 1
            self?.searchHotelList()
        }
        
        self.tabView.es.addInfiniteScrolling {[weak self] in
            self?.page += 1
            self?.searchHotelList()
        }
    }
    
    
    @objc func gotoHotel(dic:Notification){
        
        let data = dic.object as! Dictionary<String, Any>
        
        
            let vc = HotelDetailsController()
            vc.time2 = time2
            vc.time1 = time1
            vc.cityId = cityId
        
        print("\(data)")

        vc.hotelId = "\(data["sourceHotelCode"] ?? "")"
            self.navigationController?.pushViewController(vc, animated: true)
        
    }

    func locationStart() {
        //判断是否允许定位
        if CLLocationManager.locationServicesEnabled() {
            self.locationManager.delegate = self
            //设置定位精度
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            //每隔多少米定位一次（这里的设置为每隔百米)
            self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
            self.locationManager.requestWhenInUseAuthorization()
            //开始定位
            self.locationManager.startUpdatingLocation()
        }else{
            YProgressHUD.showToast("定位服务当前可能尚未打开，请设置打开！")
        }
    }
    
    @objc func calendar(notifi : Notification) {
        
        let dic = notifi.userInfo
        let key = "\(dic?["key"] ?? "")"
        if key == "0" {
            GKCover.hideWithoutAnimation()
            return
        }
        let data1 = "\(dic?["data1"] ?? "")"
        let data2 = "\(dic?["data2"] ?? "")"
        let day = "\(dic?["day"] ?? "")"
        
        if data1.isEmpty  {
            YProgressHUD.showToast("入住时间不能为空")
        }else{
            if data2.isEmpty {
                YProgressHUD.showToast("离店时间不能为空")
            }else{
                self.time1 = data1
                self.time2 = data2
                self.day = day
                self.tabView.reloadData()
                GKCover.hideWithoutAnimation()
            }
        }
        
   }
    
    func headScreening(view:UIView) {
        if (GKCover.hasCover()) {
            GKCover.hide {
            }
        }
        let view1 = UIView.init()
        view1.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        view1.backgroundColor = UIColor.clear
        self.view.addSubview(view1)
        GKCover.cover(from: view1, contentView: view, style: .translucent, showStyle: .bottom, showAnimStyle: .none, hideAnimStyle: .none, notClick: false) {
            
        } hide: {
            view1.removeFromSuperview()
        }
        
    }

    @IBAction func backBtn(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    

    
    //根据城市名称获取城市id接口
    func getCityIdByName(country:String,province:String,city:String,district:String) {
        cancelableRequest = NetWorkRequest(API1.getCityIdByName(parameters: ["country":country,"province":province,"city":city,"district":district]), completion: {[weak self] (responseString) -> (Void) in
            self?.areaId = responseString["data"]["areaId"].stringValue
            self?.cityId = responseString["data"]["cityId"].stringValue
            self?.getHotelCondition()
            self?.tabView.header?.startRefreshing()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    //获取酒店筛选条件
    func getHotelCondition() {
        cancelableRequest = NetWorkRequest(API1.getHotelCondition(parameters: ["cityId":self.cityId]), completion: {[weak self] (responseString) -> (Void) in
            self?.priceList = responseString["data"]["priceList"].arrayObject
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常,超时")
        })
    }
    
    //获取酒店列表接口
    func searchHotelList() {
        cancelableRequest = NetWorkRequest(API1.searchHotelList(parameters: ["cityId":self.cityId,"checkInDate":self.time1,"checkOutDate":self.time2,"sortType":"1","pageIndex":self.page,"pageCount":"10"]), completion: {[weak self] (responseString) -> (Void) in
            let data = responseString["data"]["hotelList"].arrayObject
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            if let array = data {
                self?.mutDataDic.updateValue((array as NSArray?)!, forKey: self!.page)
                self?.dataSouce.removeAll()
                for item in 1...self!.page {
                    let ar = (self?.mutDataDic[item] ?? []) as NSArray
                    for item in ar {
                        self?.dataSouce.append(item as! NSDictionary)
                    }
                }
            }else{
                self?.mutDataDic.updateValue(([]), forKey: self!.page)
                self?.dataSouce.removeAll()
                for item in 1...self!.page {
                    let ar = (self?.mutDataDic[item] ?? []) as NSArray
                    for item in ar {
                        self?.dataSouce.append(item as! NSDictionary)
                    }
                }
            }
            self?.guessLikeView.setUpdata(array:self?.dataSouce ?? [])
            self?.tabView.reloadData()
        }, failed: {[weak self] (failedResutl) -> (Void) in
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: {[weak self] () -> (Void) in
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            print("网络异常,超时")
        })
    }
}

extension HotelHomeController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.row {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyBanner) as! HomeBannerCell
            cell.selectionStyle = .none
            cell.stateLab.text = self.time1
            cell.endLab.text = self.time2
            cell.numberLab.text = "共\(self.day)晚"
            cell.backView.addSubview(self.banner)
            cell.hotelBtn.addTarget(self, action: #selector(hotel), for: .touchUpInside)
//            cell.hourRoomBtn.addTarget(self, action: #selector(hourRoom), for: .touchUpInside)
//            cell.stayFacilityBtn.addTarget(self, action: #selector(stayFacility), for: .touchUpInside)
            cell.aFewLab.text = "\(self.jian)间," + " \(self.cr)成人," + " \(self.er)儿童"
            if self.number == 0 {
                cell.hotelBtn.isSelected = true
//                cell.stayFacilityBtn.isSelected = false
//                cell.hourRoomBtn.isSelected = false
            }else if self.number == 1 {
                cell.hotelBtn.isSelected = false
//                cell.stayFacilityBtn.isSelected = false
//                cell.hourRoomBtn.isSelected = true
            }else if self.number == 2 {
                cell.hotelBtn.isSelected = false
//                cell.stayFacilityBtn.isSelected = true
//                cell.hourRoomBtn.isSelected = false
            }
            cell.starTf.delegate = self
            if let price = self.priceDic, let star = self.starDic {
                cell.starTf.text = "\(price["keyword"] ?? "")/\(star["name"] ?? "")"
            }
            cell.seachTf.text = self.seachStr
            cell.seachTf.tag = 1
            cell.seachTf.delegate = self
            cell.addressLab.text = self.chooseCity
            cell.numberBtn.addTarget(self, action: #selector(numberBtn), for: .touchUpInside)
            cell.queryBtn.addTarget(self, action: #selector(query), for: .touchUpInside)
            cell.addressBtn.addTarget(self, action: #selector(address), for: .touchUpInside)
            cell.switchAddressBtn.addTarget(self, action: #selector(switchAddress), for: .touchUpInside)
            cell.timeBtn.addTarget(self, action: #selector(timeChooes), for: .touchUpInside)
            
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyPC) as! Pure1Cell
            cell.selectionStyle = .none
            self.guessLikeView.bindViewToViewModel(collView: cell.collVIew)
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.row {
        case 0:
            return 292 + 202
        default:
            let i = self.dataSouce.count / 2
            var j = self.dataSouce.count % 2
            if j > 0 {
                j = 1
            }
            let h = CGFloat(((SCREEN_WIDTH - 40) / 2 + 120))
            let g = j + i
            return h * CGFloat(g) + 10.0
        }
        
    }
    //酒店
    @objc func hotel() {
        self.number = 0
        self.tabView.reloadData()
    }
    //钟点房
    @objc func hourRoom() {
        self.number = 1
        self.tabView.reloadData()
    }
    //民宿
    @objc func stayFacility() {
        self.number = 2
        self.tabView.reloadData()
    }
    @objc func numberBtn() {
        self.homePopupView.show()
    }
    //定位
    @objc func address(){
        self.locationStart()
    }
    //切换地址
    @objc func switchAddress(){
        self.switchAddressView.positioning(city: self.currCity)
        self.switchAddressView.show()
    }
    //时间切换
    @objc func timeChooes(){
        self.headScreening(view: self.calendarSelectView)
    }
    //查询
    @objc func query() {
        let vc = HotelQueryListController()
        vc.currCity = self.chooseCity
        vc.areaId = self.areaId
        vc.cityId = self.cityId
        vc.time1 = self.time1
        vc.time2 = self.time2
        vc.day = self.day
        //间数，成人，儿童
        vc.jian = self.jian
        vc.cr = self.cr
        vc.er = self.er
        vc.seachStr = self.seachStr
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension HotelHomeController:JXBannerDataSource,JXBannerDelegate{
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return 3
    }
    
    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {
        return JXBannerCellRegister(type: nil,
                                    reuseIdentifier: "HomeBannerColl",
                                    nib: UINib(nibName: "HomeBannerColl", bundle: Bundle.main))
    }
    
    func jxBanner(_ banner: JXBannerType, cellForItemAt index: Int, cell: UICollectionViewCell) -> UICollectionViewCell {
        if let tempCell = cell as? HomeBannerColl {
//            if let array = self.banners {
//                let dic = array[index] as! Dictionary<String,Any>
//                tempCell.img.kf.setImage(with: URL.init(string: "\(dic["img"] ?? "")"))
//
//            }
            tempCell.img.image = UIImage.init(named: "图层59")
        }
        return cell
    }
    
    func jxBanner(_ banner: JXBannerType,
                  layoutParams: JXBannerLayoutParams)
        -> JXBannerLayoutParams {
        return layoutParams
            .itemSize(CGSize(width: SCREEN_WIDTH, height: 203))
    }
    
    func jxBanner(pageControl banner: JXBannerType, numberOfPages: Int, coverView: UIView, builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {
        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottomRight
        pageControl.activeSize = CGSize(width: 15, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = UIColor.white
        pageControl.inactiveColor = UIColor.white
        pageControl.columnSpacing = 0
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.left.right.equalTo(coverView)
                maker.top.equalTo(coverView.snp.bottom).offset(-80)
                maker.height.equalTo(20)
            }
        }
        return builder
    }
    
    func jxBanner(_ banner: JXBannerType, params: JXBannerParams) -> JXBannerParams {
        return params.timeInterval(3)
    }
    
    func jxBanner(_ banner: JXBannerType,
                      didSelectItemAt index: Int) {
        
    }

}

extension HotelHomeController:GuessLikeDelegate{
    
    
  
    func guessLikeClick(data: NSDictionary) {

    }
}

extension HotelHomeController:StayInDelegate{
    func stayInClick(data: Dictionary<String, Any>) {
        self.jian = "\(data["jian"] ?? "0")"
        self.cr = "\(data["cr"] ?? "0")"
        self.er = "\(data["er"] ?? "0")"
        self.tabView.reloadData()
    }
}

extension HotelHomeController:PriceStarDelegate{
    func priceStarClick(priceDic: Dictionary<String, Any>, starDic: Dictionary<String, Any>) {
        self.priceDic = priceDic
        self.starDic = starDic
        self.tabView.reloadData()
    }
    
}

extension HotelHomeController:SwitchAddressDelegate{
    func switchAddressClick(data: Dictionary<String, Any>, type: Int) {
        if type == 1 {
            self.cityId = "\(data["id"] ?? "")"
            self.chooseCity = "\(data["name"] ?? "")"
        }else{//定位
            self.locationStart()
        }
        self.switchAddressView.hide()
        self.switchAddressView.hideKeyboard()
        self.tabView.reloadData()
    }
    
}

extension HotelHomeController:CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
        self.locationManager.stopUpdatingLocation()
        //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
        let currentLocation = locations.last
        //获取当前所在的城市名
        let geocoder = CLGeocoder.init()
        if let current = currentLocation {
            //根据经纬度反向地理编译出地址信息
            geocoder.reverseGeocodeLocation(current) { array, error in
                if let locats = array {
                    if locats.count > 0 {
                        let placemark = locats[0]
                        //获取城市
                        self.currCity = placemark.locality ?? ""
                        if self.currCity.isEmpty == true{
                            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                            self.currCity = placemark.administrativeArea ?? ""
                        }
                        self.chooseCity = self.currCity
                        self.tabView.reloadData()
                        self.getCityIdByName(country: placemark.country ?? "", province: placemark.administrativeArea ?? "", city: self.chooseCity, district: placemark.subLocality ?? "")
                    }
                }
            }
        }
        
        
    }
}

extension HotelHomeController:UITextFieldDelegate{
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
        if textField.tag == 1 {
            return true
        }
        if let array = self.priceList {
            self.priceStarView.setUpData(array: array)
            self.headScreening(view: self.priceStarView)
        }
        return false
    }
    
    func textFieldDidEndEditing(_ textField: UITextField){
        self.seachStr = textField.text ?? ""
    }
}
